<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-withdraw container">
    <view class="form-title">
      店铺名称
    </view>
    <view class="form-item">
      <view style="font-size:28rpx">
        {{ dataForm.shopName }}
      </view>
    </view>
    <view class="form-title">
      提现金额<text class="form-title-desc">
        （可提现余额：{{ withdrawAmount }}）
      </text>
    </view>
    <view
      class="form-item form-item-input"
      style="height:40rpx"
    >
      <input
        v-model="dataForm.amount"
        type="number"
        placeholder="输入提现金额"
      >
      <view
        class="form-item-button"
        @tap="()=>{dataForm.amount=withdrawAmount}"
      >
        全部提现
      </view>
    </view>
    <text class="required">
      *
    </text><view class="form-title">
      到账银行卡
    </view>
    <view class="form-item">
      <text style="font-size:28rpx">
        {{ selectedBank.bankName }}
      </text><view
        class="form-item-button"
        @tap="chooseBank"
      >
        选择银行卡
      </view>
    </view>
    <text class="required">
      *
    </text><view class="form-title">
      短信验证
      <text
        v-if="paySettlementType===1"
        class="form-title-desc"
      >
        （手机尾号{{ receiveMobile }}）
      </text>
    </view>
    <view class="form-item form-item-input code">
      <input
        v-model="dataForm.code"
        type="number"
        maxlength="6"
        placeholder="输入验证码"
      >
      <view
        v-if="!showCount"
        class="form-item-button"
        @tap="sendCode"
      >
        获取验证码
      </view>
      <view
        v-else
        class="form-item-count"
      >
        {{ count }}
      </view>
    </view>
    <view
      v-if="paySettlementType===1"
      class="code-tip"
    >
      验证码将发送到银行卡预留手机号，发送验证码后将会冻结本次提现金额且不可撤回，请谨慎操作
    </view>
    <view class="form-title">
      备注
    </view>
    <view class="form-item">
      <textarea
        :value="dataForm.shopRemarks"
        placeholder="最多60字，特殊字符会被过滤"
        :maxlength="60"
        style="height:160rpx"
        @input="handleInput"
      />
    </view>

    <view
      class="button-submit"
      @tap="dataFormSubmit"
    >
      <text>提交申请</text>
    </view>
  </view>
</template>
<script setup>
import { onMounted } from 'vue'

const paySettlementType = uni.getStorageSync('bbcPaySettlementType')
const dataForm = reactive({
  amount: null, // 提现余额
  shopName: '', // 店铺名称
  shopRemarks: null, // 备注
  code: null, // 验证码
  shopBankCardId: '' // 当前选择的银行卡id
})
let bankList = [] // 银行列表
const selectedBank = ref({}) // 所选银行
let isSendCode = false
const withdrawAmount = ref(null) // 总
const receiveMobile = ref(null)
const count = ref(null) // 计数
const showCount = ref(false) // 计数显示
let currentIndex = null // 当前银行卡索引
onLoad(() => {
  uni.showLoading({
    title: '加载中'
  })
  // 监听选择银行事件
  uni.$on('page-withdraw-setCurrentIndex', (val) => {
    currentIndex = val
  })
  const ProMobile = new Promise((resolve) => {
    const params = {
      url: '/shop/shopDetail/info',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      receiveMobile.value = data.adminMobile?.slice(-4)
      resolve()
    })
  }
  )

  const ProWallet = new Promise((resolve) => {
    const params = {
      url: '/shop/withdrawCash/getShopInfo',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      withdrawAmount.value = data.amount
      dataForm.shopName = data.shopName
      resolve()
    })
  })

  const ProBank = new Promise((resolve) => {
    const params = {
      url: '/shop/shopBankCard/getShopBankCardList',
      method: 'GET'
    }
    http.request(params).then(({ data }) => {
      currentIndex = data.findIndex(item => item.isDefault)
      bankList = data
      getBankData(currentIndex)
      resolve()
    })
  })

  Promise.all([ProMobile, ProWallet, ProBank]).then(() => {
    uni.hideLoading()
  })
})

onMounted(() => {
  isFirstSend = true
  if (paySettlementType === 1) {
    getPlatformWithdrawalSetting()
  }
})
onUnload(() => {
  uni.$off('page-withdraw-setCurrentIndex')
})
onShow(() => {
  if (bankList.length !== 0 && currentIndex != null) {
    getBankData(currentIndex)
  }
})

// 获取平台提现设置
let platformWithdrawalSetting = {} // 平台提现设置
const getPlatformWithdrawalSetting = () => {
  http.request({
    url: '/shop/withdrawCash/getWithdrawCash',
    method: 'get'
  }).then(({ data }) => {
    platformWithdrawalSetting = data
  })
}

/**
 * 根据索引得到银行名称、id
 */
const getBankData = (index) => {
  if (index < 0) {
    index = 0
  }
  const bank = bankList[index]
  selectedBank.value = bank
  dataForm.shopBankCardId = bank.shopBankCardId
}
/**
 * 过滤特殊字符
 */
const handleInput = (value) => {
  dataForm.shopRemarks = value.detail.value.replaceAll(/[^a-zA-Z0-9\u4E00-\u9FA5.]/g, '')
}
/**
 * 发送验证码
 */
let timer = null
let isFirstSend = true // 是否首次请求验证码
let bizOrderNo = '' // 通联提现订单号
const sendCode = async () => {
  if (isSendCode) {
    return
  }

  if (paySettlementType === 1 && dataForm.amount < platformWithdrawalSetting.withdrawCashLeast) {
    uni.showToast({
      title: `提现金额不能少于${platformWithdrawalSetting.withdrawCashLeast}元`,
      icon: 'none'
    })
    return
  }
  if (paySettlementType === 1 && !selectedBank.value.shopBankCardId) {
    uni.showToast({
      title: '请先选择银行卡！',
      icon: 'none',
      duration: 1000
    })
    return
  }
  if (paySettlementType === 1 && !await getMissingInfo()) {
    return
  }
  let url = '/shop/shopDetail/sendCode'
  let data = {}
  if (paySettlementType === 1) {
    data = {
      shopBankCardId: selectedBank.value.shopBankCardId,
      bankCardNo: selectedBank.value.bankCardNo,
      amount: dataForm.amount + '' || '0'
    }
    // 首次发送验证码为申请提现，非首次为重新发送验证码
    if (isFirstSend) {
      url = '/shop/withdrawCash/allinpayApply'
    } else {
      data.bizOrderNo = bizOrderNo
      url = '/shop/withdrawCash/resendPaySms'
    }
  }
  const params = {
    url,
    method: 'post',
    data: paySettlementType === 1 ? data : undefined
  }
  http.request(params).then(({ data }) => {
    isSendCode = true
    uni.showToast({
      title: '发送成功',
      duration: 2000
    })
    if (isFirstSend) {
      isFirstSend = false
    }
    // 通联支付接口返回的提现订单号，保存提现订单号
    if (paySettlementType === 1) {
      bizOrderNo = data
    }
    const timeCount = 60
    if (!showCount.value) {
      count.value = timeCount
      showCount.value = true
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          clearInterval(timer)
          isSendCode = false
          showCount.value = false
        }
      }, 1000)
    }
  })
}
const getMissingInfo = () => {
  return new Promise((resolve) => {
    http.request({
      url: '/shop/shopDetail/info',
      method: 'get'
    }).then(({ data }) => {
      const tips = []
      if (selectedBank.value.bankCardPro !== 0 && (data.companyAcctProtocolNo === null || data.companyAcctProtocolNo === '')) {
        tips.push('是否已签约对公户提现协议')
      }
      if (selectedBank.value.bankCardPro !== 1 && (data.legalAcctProtocolNo === null || data.legalAcctProtocolNo === '')) {
        tips.push('是否已签约法人提现协议')
      }
      if (data.isBindPhone !== 1) {
        tips.push('是否已绑定手机')
      }
      if (data.isCreateMember !== 1) {
        tips.push('是否已创建店铺会员')
      }
      if (data.companyInfoProcessStatus !== 2) {
        tips.push('企业信息审核状态是否正常')
      }
      if (data.idCardCollectProcessStatus !== 4) {
        tips.push('影印件状态是否正常')
      }
      if (tips.length > 0) {
        uni.showToast({
          title: `请确认${tips.join('、')}！`,
          icon: 'none',
          duration: 1500
        })
        resolve(false)
      }
      resolve(true)
    })
  })
}
/**
 * 表单提交
 */
const dataFormSubmit = () => {
  if (!dataForm.amount) {
    // console.log('codeerror')
    uni.showToast({
      title: '余额不为空！',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (paySettlementType === 1 && dataForm.amount < platformWithdrawalSetting.withdrawCashLeast) {
    uni.showToast({
      title: `提现金额不能少于${platformWithdrawalSetting.withdrawCashLeast}元`,
      icon: 'none'
    })
    return
  }
  if (dataForm.amount < 1 && paySettlementType !== 1) {
    uni.showToast({
      title: '提现金额不能少于1.00元',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (!dataForm.code || (paySettlementType === 1 && !bizOrderNo)) {
    uni.showToast({
      title: '验证码不为空',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  let data = {}
  let url = '/shop/withdrawCash/apply'
  if (paySettlementType === 1) {
    url = '/shop/withdrawCash/confirmWithdrawPay'
    data = {
      bankCardNo: selectedBank.value.bankCardNo,
      amount: (dataForm.amount + '') || '0',
      bizOrderNo,
      verificationCode: dataForm.code
    }
  }
  const params = {
    url,
    method: 'post',
    data: paySettlementType === 1 ? data : dataForm
  }
  http.request(params).then((res) => {
    if (res.code === '00000') {
      uni.navigateBack({
        delta: 1
      })
    } else {
      uni.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  })
}
/**
 * 选择银行卡
 */
const chooseBank = () => {
  uni.navigateTo({ url: '/pages/bank-select/bank-select?currentIndex=' + currentIndex })
}

</script>

<style lang="scss" scoped>
@import './withdraw.scss';
</style>
